<div th:fragment="contentItems">
    <!-- 搜索表单 -->
    <div class="search-form mb-4">
        <form id="searchForm">
            <div class="row g-3 mb-2">
                <div class="col-md-4">
                    <input type="text" class="form-control" id="itemKey" placeholder="语言包Key">
                </div>
                <div class="col-md-4">
                    <input type="text" class="form-control" id="fromTable" placeholder="业务表名">
                </div>
                <div class="col-md-4">
                    <input type="text" class="form-control" id="fromField" placeholder="字段名">
                </div>
            </div>
            <div class="row g-3 align-items-center">
                <div class="col-md-4">
                    <input type="text" class="form-control" id="fromDataId" placeholder="数据ID">
                </div>
                <div class="col-md-4">
                    <input type="text" class="form-control" id="memo" placeholder="备注">
                </div>
                <div class="col-md-4 d-flex gap-2 justify-content-end">
                    <button type="submit" class="btn btn-primary">搜索</button>
                    <button type="reset" class="btn btn-secondary">重置</button>
                    <button type="button" class="btn btn-success" onclick="showAddModal()">
                        <i class="bi bi-plus"></i> 新增语言包
                    </button>
                </div>
            </div>
        </form>
    </div>
    <!-- 数据表格 -->
    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>语言包Key</th>
                            <th>业务表名</th>
                            <th>字段名</th>
                            <th>数据ID</th>
                            <th>备注</th>
                            <th>更新时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="itemsTableBody">
                        <!-- 数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
            <!-- 分页控件 -->
            <nav aria-label="Page navigation">
                <ul class="pagination justify-content-center" id="pagination">
                    <!-- 分页将通过JavaScript动态加载 -->
                </ul>
            </nav>
        </div>
    </div>
    <!-- 新增/编辑模态框 -->
    <div class="modal fade" id="itemModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">新增语言包</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="itemForm">
                        <div class="mb-3">
                            <label class="form-label">语言包Key</label>
                            <input type="text" class="form-control" id="itemKeyInput" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">业务表名</label>
                            <input type="text" class="form-control" id="fromTableInput">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">字段名</label>
                            <input type="text" class="form-control" id="fromFieldInput">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">数据ID</label>
                            <input type="text" class="form-control" id="fromDataIdInput">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">备注</label>
                            <input type="text" class="form-control" id="memoInput">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveItemButton">保存</button>
                </div>
            </div>
        </div>
    </div>
    <!-- 编辑模态框 -->
    <div class="modal fade" id="editModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑语言包</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editForm">
                        <input type="hidden" id="editItemKey">
                        <div id="langContentContainer">
                            <!-- 语言内容将通过JavaScript动态加载 -->
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveButton">保存</button>
                </div>
            </div>
        </div>
    </div>
    <script src="/js/bootstrap.bundle.min.js"></script>
    <script src="/js/axios.min.js"></script>
    <script>
        let currentPage = 1;
        const pageSize = 10;
        let totalPages = 1;
        let isEdit = false;
        document.addEventListener('DOMContentLoaded', function() {
            loadItems();
            setupEventListeners();
        });
        function setupEventListeners() {
            document.getElementById('searchForm').addEventListener('submit', function(e) {
                e.preventDefault();
                currentPage = 1;
                loadItems();
            });
            document.getElementById('saveButton').addEventListener('click', saveContent);
            document.getElementById('saveItemButton').addEventListener('click', saveItem);
        }
        function showAddModal() {
            isEdit = false;
            document.getElementById('modalTitle').textContent = '新增语言包';
            document.getElementById('itemForm').reset();
            new bootstrap.Modal(document.getElementById('itemModal')).show();
        }
        function saveItem() {
            const data = {
                itemKey: document.getElementById('itemKeyInput').value,
                fromTable: document.getElementById('fromTableInput').value,
                fromField: document.getElementById('fromFieldInput').value,
                fromDataId: document.getElementById('fromDataIdInput').value,
                memo: document.getElementById('memoInput').value,
                operator: 'admin'
            };
            axios.post('/translate/itemKey', {
                fromTable: data.fromTable,
                fromField: data.fromField,
                description: data.memo,
                operator: data.operator
            })
            .then(response => {
                if (response.data.code === 200) {
                    data.itemKey = response.data.data;
                    return axios.post('/translate/content/save', {
                        itemKey: data.itemKey,
                        langCode: 'zh',
                        content: data.memo,
                        operator: data.operator
                    });
                }
            })
            .then(response => {
                if (response.data.code === 200) {
                    alert('保存成功');
                    bootstrap.Modal.getInstance(document.getElementById('itemModal')).hide();
                    loadItems();
                }
            })
            .catch(error => {
                console.error('保存失败:', error);
                alert('保存失败，请重试');
            });
        }
        function loadItems() {
            axios.post('/translate/items', {
                pageNum: currentPage,
                pageSize: pageSize,
                itemKey: document.getElementById('itemKey').value,
                fromTable: document.getElementById('fromTable').value,
                fromField: document.getElementById('fromField').value,
                fromDataId: document.getElementById('fromDataId').value,
                memo: document.getElementById('memo').value
            })
            .then(response => {
                if (response.data.code === 200) {
                    const data = response.data.data;
                    renderItems(data.records);
                    renderPagination(data.total);
                }
            })
            .catch(error => {
                console.error('加载数据失败:', error);
                alert('加载数据失败，请重试');
            });
        }
        function renderItems(items) {
            const tbody = document.getElementById('itemsTableBody');
            tbody.innerHTML = items.map(item => `
                <tr>
                    <td>${item.itemKey}</td>
                    <td>${item.fromTable || '-'}</td>
                    <td>${item.fromField || '-'}</td>
                    <td>${item.fromDataId || '-'}</td>
                    <td>${item.memo || '-'}</td>
                    <td>${new Date(item.updateTime).toLocaleString()}</td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="editItem('${item.itemKey}')">
                            <i class="bi bi-pencil"></i> 编辑
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="deleteItem('${item.itemKey}')">
                            <i class="bi bi-trash"></i> 删除
                        </button>
                    </td>
                </tr>
            `).join('');
        }
        function renderPagination(total) {
            totalPages = Math.ceil(total / pageSize);
            const pagination = document.getElementById('pagination');
            let html = '';
            html += `
                <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="changePage(${currentPage - 1})">上一页</a>
                </li>
            `;
            for (let i = 1; i <= totalPages; i++) {
                html += `
                    <li class="page-item ${currentPage === i ? 'active' : ''}">
                        <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
                    </li>
                `;
            }
            html += `
                <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="changePage(${currentPage + 1})">下一页</a>
                </li>
            `;
            pagination.innerHTML = html;
        }
        function changePage(page) {
            if (page < 1 || page > totalPages) return;
            currentPage = page;
            loadItems();
        }
        function editItem(itemKey) {
            document.getElementById('editItemKey').value = itemKey;
            axios.post('/translate/fullContent', {
                itemKey: itemKey
            })
            .then(response => {
                if (response.data.code === 200) {
                    const data = response.data.data;
                    renderEditForm(data);
                    new bootstrap.Modal(document.getElementById('editModal')).show();
                }
            })
            .catch(error => {
                console.error('加载语言包内容失败:', error);
                alert('加载语言包内容失败，请重试');
            });
        }
        function renderEditForm(data) {
            const container = document.getElementById('langContentContainer');
            container.innerHTML = data.contentList.map(content => `
                <div class="mb-3">
                    <label class="form-label">${content.langCode}</label>
                    <textarea class="form-control" name="content_${content.langCode}">${content.content}</textarea>
                </div>
            `).join('');
        }
        function saveContent() {
            const itemKey = document.getElementById('editItemKey').value;
            const contentList = [];
            document.querySelectorAll('[name^="content_"]').forEach(input => {
                const langCode = input.name.replace('content_', '');
                contentList.push({
                    langCode: langCode,
                    content: input.value
                });
            });
            const data = {
                itemKey: itemKey,
                contentList: contentList
            };
            axios.post('/admin/translate/fullContent/save', data)
                .then(response => {
                    if (response.data.code === 200) {
                        alert('保存成功');
                        bootstrap.Modal.getInstance(document.getElementById('editModal')).hide();
                        loadItems();
                    }
                })
                .catch(error => {
                    console.error('保存失败:', error);
                    alert('保存失败，请重试');
                });
        }
        function deleteItem(itemKey) {
            if (!confirm('确定要删除这个语言包吗？')) return;
            axios.post('/translate/content/remove', {
                itemKey: itemKey,
                operator: 'admin'
            })
            .then(response => {
                if (response.data.code === 200) {
                    alert('删除成功');
                    loadItems();
                }
            })
            .catch(error => {
                console.error('删除失败:', error);
                alert('删除失败，请重试');
            });
        }
    </script>
</div> 